//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"context"
	"net"

	"atomgit.com/openlinksaas/netutil/gen_code"
)

type DnsApiImpl struct{}

func (s *DnsApiImpl) DnsQueryPost(ctx context.Context, req gen_code.DnsQueryPostRequest) (gen_code.ImplResponse, error) {
	if req.Token != token {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: "wrong token",
			},
		}, nil
	}
	ipList := []string{}
	ipResList, err := net.DefaultResolver.LookupIP(ctx, "ip", req.Addr)
	if err == nil {
		for _, ipRes := range ipResList {
			ipList = append(ipList, ipRes.String())
		}
	}
	cname, _ := net.DefaultResolver.LookupCNAME(ctx, req.Addr)
	mxList := []gen_code.DnsQueryPost200ResponseMxInner{}
	mxResList, err := net.DefaultResolver.LookupMX(ctx, req.Addr)
	if err == nil {
		for _, mxRes := range mxResList {
			mxList = append(mxList, gen_code.DnsQueryPost200ResponseMxInner{
				Host: mxRes.Host,
				Pref: int32(mxRes.Pref),
			})
		}
	}
	txtList, err := net.DefaultResolver.LookupTXT(ctx, req.Addr)
	if err != nil {
		txtList = []string{}
	}
	return gen_code.ImplResponse{
		Code: 200,
		Body: gen_code.DnsQueryPost200Response{
			A:     ipList,
			Cname: cname,
			Mx:    mxList,
			Txt:   txtList,
		},
	}, nil
}
